import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import ScaleBar from '@arcgis/core/widgets/ScaleBar'
import Home from '@arcgis/core/widgets/Home'
import Expand from '@arcgis/core/widgets/Expand'
import LayerList from '@arcgis/core/widgets/LayerList'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import { gaodeImageLayer } from '@/utils/GaoDeBaseLayer'
// 导入地块操作模块
import {
  useLandParcelOperations,
  operationState,
  landParcelForm,
  landTypeOptions,
} from '@/utils/LandParcelOperations'

export function useMapView() {
  const router = useRouter()
  const userStore = useUserStore()

  // 检查用户是否已登录
  if (!userStore.isLogin) {
    router.push('/')
  }

  // 地图相关引用
  const mapDiv = ref<HTMLDivElement | null>(null)
  let mapView: MapView | null = null
  let map: Map | null = null

  // 图层控制状态
  const layerVisibility = ref({
    landParcel: true,
    landChange: true,
  })

  // 底图类型控制
  const baseMapType = ref('vector') // 'vector' 矢量图 或 'image' 影像图

  // 侧边栏控制
  const isCollapse = ref(false)
  const activeMenu = ref('1')

  // 用户角色
  const userRole = ref(userStore.userRole)

  // 初始化地块操作
  let landParcelOps: ReturnType<typeof useLandParcelOperations> | null = null

  // 初始化地图
  const initMap = () => {
    if (!mapDiv.value) return null

    // 创建地图实例
    map = new Map({
      basemap: {
        baseLayers: [baseMapType.value === 'vector' ? gaodeLayer : gaodeImageLayer],
      },
    })

    // 创建地块图层
    const landParcelLayer = new FeatureLayer({
      url: 'https://services5.arcgis.com/4AiL0yfsDkakGbRW/arcgis/rest/services/landFeaturelayer/FeatureServer/0',
      outFields: ['*'],
      title: '土地地块图层',
      id: 'landParcelLayer',
    })

    // 添加图层到地图
    map.add(landParcelLayer)

    // 创建地图视图
    mapView = new MapView({
      container: mapDiv.value,
      map: map,
      zoom: 12,
      center: [116.3, 39.9],
    })

    // 添加比例尺
    const scaleBar = new ScaleBar({
      view: mapView,
      unit: 'metric',
      style: 'ruler',
    })
    mapView.ui.add(scaleBar, {
      position: 'bottom-left',
    })

    // 添加Home按钮（全图显示）
    const homeBtn = new Home({
      view: mapView,
    })
    mapView.ui.add(homeBtn, {
      position: 'top-left',
    })

    // 添加图层列表
    const layerList = new LayerList({
      view: mapView,
    })
    const layerListExpand = new Expand({
      view: mapView,
      content: layerList,
      group: 'top-right',
    })
    mapView.ui.add(layerListExpand, {
      position: 'top-right',
    })

    // 如果是管理员，添加编辑工具
    if (userRole.value === 'admin') {
      // 创建图形图层用于编辑
      const graphicsLayer = new GraphicsLayer({
        id: 'editGraphicsLayer',
        title: '编辑图层',
      })
      map.add(graphicsLayer)

      // 初始化地块操作
      landParcelOps = useLandParcelOperations(mapView, map)
      landParcelOps.initLandParcelOperations()
    }

    // 返回地图实例和地图视图，供其他模块使用
    return { map, mapView }
  }

  // 切换底图类型
  const toggleBaseMap = () => {
    if (!map) return

    baseMapType.value = baseMapType.value === 'vector' ? 'image' : 'vector'

    // 更新地图底图
    map.basemap!.baseLayers.removeAll()
    map.basemap!.baseLayers.add(baseMapType.value === 'vector' ? gaodeLayer : gaodeImageLayer)
  }

  // 监听图层可见性变化
  watch(
    () => layerVisibility.value,
    (newVal) => {
      if (!map) return

      const landParcelLayer = map.findLayerById('landParcelLayer')
      if (landParcelLayer) {
        landParcelLayer.visible = newVal.landParcel
      }

      const landChangeLayer = map.findLayerById('landChangeLayer')
      if (landChangeLayer) {
        landChangeLayer.visible = newVal.landChange
      }
    },
    { deep: true },
  )

  // 退出登录
  const handleLogout = () => {
    userStore.logout()
    router.push('/')
  }

  // 地块操作方法
  const handleAddLandParcel = () => {
    if (landParcelOps) {
      landParcelOps.startDrawLandParcel()
    }
  }

  const handleEditLandParcel = () => {
    if (landParcelOps) {
      landParcelOps.startEditLandParcel()
    }
  }

  const handleDeleteLandParcel = () => {
    if (landParcelOps) {
      landParcelOps.deleteLandParcel()
    }
  }

  const handleCancelDraw = () => {
    if (landParcelOps) {
      landParcelOps.cancelDraw()
    }
  }

  const handleSubmitAdd = () => {
    if (landParcelOps) {
      landParcelOps.submitAddLandParcel()
    }
  }

  const handleSubmitEdit = () => {
    if (landParcelOps) {
      landParcelOps.submitEditLandParcel()
    }
  }

  const handleCloseAttributePanel = () => {
    if (landParcelOps) {
      landParcelOps.closeAttributePanel()
    }
  }

  return {
    mapDiv,
    layerVisibility,
    baseMapType,
    isCollapse,
    activeMenu,
    userRole,
    initMap,
    toggleBaseMap,
    handleLogout,
    // 导出地块操作状态和方法
    operationState,
    landParcelForm,
    landTypeOptions,
    handleAddLandParcel,
    handleEditLandParcel,
    handleDeleteLandParcel,
    handleCancelDraw,
    handleSubmitAdd,
    handleSubmitEdit,
    handleCloseAttributePanel,
  }
}
